var request = require('request');
var moment = require('moment');
var md5 = require('md5');
var db = require('../config/mongo_database');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');
var logger = require('../config/log4js').logger('access');
var sms = require('../route/sms');


exports.signin = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';

	db.userModel.findOne({username: username}, function (err, user) {
		if (err || null==user) {
			// 可添加安全登录次数校验
			return res.json({status:401, msg:'账号不存在，请先注册'});
		}
		user.comparePassword(password, function(isMatch) {
			if (!isMatch) {
				return res.json({status:401, msg:'账号或密码错误'});
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
            redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
			return res.json({status:200, token:token});
		});

	});
};

exports.register = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';
	var smscode = req.body.smscode || '';
	if (username == '' || password == '') {
		return res.json({status:400, msg:'账号或密码不能为空'});
	}
	redisClient.get(username, function(err, code) {
		if(err || smscode!=code) 
			return res.json({status:501, msg:'验证码有误'});
		if(smscode==code){ 
			fastRegister(res, username, password)
		}
	});
	
}

exports.forget = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';
	var smscode = req.body.smscode || '';
	if (username == '' || password == '') {
		return res.json({status:400, msg:'账号或密码不能为空'});
	}
	redisClient.get(username, function(err, code) {
		if(err || smscode!=code) 
			return res.json({status:501, msg:'验证码有误'});
		if(smscode==code){ 
			fastForget(res, username, password)
		}
	});
	
}

//  获取用户信息
exports.me = function(req, res, next){
	var userid = tokenManager.getUserId(req);
	db.userModel.findOne({_id:userid}, 
		{username:1,email:1,header:1,score:1,grade:1,address:1}, 
		function (err, user) {
			res.json(user); 
	})
}

// 发送短信
exports.send = function(req, res){
	var username = req.body.username || '';
	if(username.trim()!=''){
		var SMS_CODE = moment(new Date()).format("mmssSS"); //验证码
		sms.send(username, 2, [SMS_CODE])
		redisClient.set(username, SMS_CODE);
        redisClient.expire(username, 60*5);
        res.json({status:200, msg:'发送成功'}); 
	}else{
		res.json({status:404, msg:'手机号不正常'});
	}
}


// 修改密码
exports.setting = function(req, res, next){
	var password = req.body.password || '';
	var email    = req.body.email || '';
	var address  = req.body.address || '';
	var type  =  req.body.type || '';
	var update = {};
	if(type == 1)
		update = {password: md5(password)};
	else if(type == 2)
		update = {email: email};
	else if(type == 3)
		update = {address: address};
	var userid = tokenManager.getUserId(req);
	db.userModel.findOne({_id:userid}, function (err, user) {
		if(err) res.sendStatus(500); 
		if(null!=user){
			db.userModel.update({_id:userid}, {$set:update}, function(err, pwduser){ // 执行变更
				res.sendStatus(200); 
			})
		}
	})
}

exports.logout = function(req, res) {
	if (req.user) {
		tokenManager.expireToken(req.headers);

		delete req.user;	
		return res.sendStatus(200);
	}
	else {
		return res.sendStatus(401);
	}
}

function fastRegister(res, username, password){
	db.userModel.findOne({username: username}, function (err, user) {
		if (user != null) {
			// 改成忘记密码， 更新密码
			return res.json({status:405, msg:'该手机号已被注册'});
		}else{
			var user = new db.userModel();
			user.username = username;
			user.nick     = username.substr(0,3) + '***' + username.substr(8,3);
			user.header   = '/assets/img/cat-'+Math.round(Math.random()*9+1)+'.png';
			user.password = password;
			user.save(function(err) {
				return res.json({status:200, msg:'注册成功'});
			});
		}
	});
}

function fastForget(res, username, password){
	db.userModel.findOne({username: username}, function (err, user) {
		if (user != null) {
			db.userModel.update({username: username}, {$set:{password:md5(password)}},function (err) {
				if(err)
					return res.json({status:501, msg:'修改密码失败！'});
				return res.json({status:200, msg:'修改密码成功'});
			})
		}else{
			return res.json({status:405, msg:'账号不存在修改失败'});
		}
	});
}

